import useCreation from "./useCreation.ts"
import useLatest from "./uselatest.ts"
import useUpdate from "./useUpdate.ts"

const observer = <T extends Record<string, any>>(
  initialVal: T,
  cb: () => void
): T => {
  const proxy = new Proxy(initialVal, {
    get(target, key, receiver) {
      const res = Reflect.get(target, key, receiver)
      // 如果属性值是一个对象，则调用 observer 函数创建响应式代理，否则直接返回属性值
      return typeof res === "object"
        ? observer(res, cb)
        : Reflect.get(target, key)
    },

    set(target, key, val) {
      const ret = Reflect.set(target, key, val)
      cb() // 调用回调函数来触发状态更新
      return ret
    },
  })

  return proxy
}

/**
 * 响应式的 useState
 * @param initialState 初始值
 * @returns
 */
const useReactive = <T extends Record<string, any>>(initialState: T): T => {
  const ref = useLatest<T>(initialState)
  const update = useUpdate()

  const state = useCreation(() => {
    return observer(ref.current, () => {
      update()
    })
  }, [])

  return state
}

export default useReactive
